<script>
import { isString } from '@/utils/kris_utils'
import { getEducation } from "@/api/basic"
import dayjs from 'dayjs'
import FormWithDialog from '@/components/EducationalExperienceForm/withDialog'
import Block from '../Block'
import Popconfirm from '@/components/PopconfirmNew/popconfirm'
import {FormStruct} from '@/components/EducationalExperienceForm/index'
export default {
    components:{
        FormWithDialog,
        Popconfirm,
        Block
    },
    props:{
        isEditing:{
            type:Boolean,
            required:true,
            default:false
        },
        value:{
            type:Array,
            required:true,
            default(){
                return []
            }
        }
    },
    data(){
        return {
            formDialog:{
                draft:{ ...FormStruct },
                visible:false,
                mode:null, // EDIT || CREATE
            },
            schoolTypeMap:new Map(),
            editingIndex:null,
            educationalLevel:[],
            tableData:[
                {
                    schoolName:'',
                    schoolType:null,//obj
                    major:'',
                    beginDate:null,
                    endDate:null,
                    certificate:'',
                    certificateNo:''
                }
            ]
        }
    },
    computed:{
        educationalExperienceFormatted(){
            // 日期需要单独处理
            const exclude = ['schoolType','beginDate','endDate']

            // 检查器
            const checker = (value) => {
                return value === undefined ||
                       value === null ||
                       (isString(value) && value.trim() === '')
            }

            return this.data.map(item => {
                let result = this.withFallback(exclude,checker,item,'未填写')
                result['schoolType'] = !result['schoolType'] ? '未填写':result['schoolType'].label
                result['beginDate'] = result['beginDate'] instanceof Date ? dayjs(result['beginDate']).format('YYYY-MM-DD'):'未填写'
                result['endDate'] = result['endDate'] instanceof Date ? dayjs(result['endDate']).format('YYYY-MM-DD'):'未填写'

                return result
            })
        },
        formDialogConfirmBtnText(){
            const { formDialog } = this,
                  m = { 'EDIT':'保存','CREATE':'添加' }

            if(formDialog.mode === null)
                return '确定'

            return m[formDialog.mode] ?? '确定'
        },
        data:{
            get(){
                return this.value
            },
            set(data){
                this.$emit('input',data)
            }
        },
        educationalLevelOptions(){
            return this.educationalLevel.map(item => {
                let option = {
                    label:item.name,
                    value:item.id
                }

                return {
                    label:item.name,
                    value:option
                }
            })
        },
    },
    methods:{
        async getEducationalLevel(){
            let result = await getEducation()
                .catch(err => {
                    throw new Error('获取学历选项失败')
                })

            if(result.code !== 200 || !Array.isArray(result.data))
                throw new Error(value(result,'message','获取学历选项失败'))


            this.educationalLevel = result.data
        },
        withFallback(exclude,checker,obj,fallback){
            const reuslt = Object
                .entries(obj)
                .map(item => {
                    if(exclude.indexOf(item[0]) !== -1)
                        return item

                    if(checker(item[1]))
                        item[1] = fallback

                    return item
                })
            return Object.fromEntries(reuslt)
        },

        handleEditing(index,row){
            this.formDialog = {
                draft:{...this.data[index]},
                mode:'EDIT',
                visible:true
            }
            this.editingIndex = index
        },

        saveRecord(){
            this.$set(this.data,this.editingIndex,{ ...this.formDialog.draft })
            this.editingIndex = null
            this.closeFormDialog()
        },
        createRecord(){
            this.data.push({ ...this.formDialog.draft })
            this.closeFormDialog()
        },
        deleteRecord(index){
            return async () => this.data.splice(index,1)
        },
        showCreateDialog(){
            this.formDialog.mode = 'CREATE'
            this.formDialog.visible = true
            this.$refs['form'].resetFields?.()
        },

        handleFormConfirm(){
            if(this.formDialog.mode === 'EDIT')
                return this.saveRecord()

            if(this.formDialog.mode === 'CREATE')
                return this.createRecord()
        },

        closeFormDialog(){
            this.formDialog.visible = false
            this.$nextTick(() => this.$refs['form'].resetFields?.())
        }
    },
    created(){
        this.getEducationalLevel()
    }
}
</script>

<template>
    <div>
        <Block title="教育经历">

            <template #extra v-if="isEditing">
                <el-button size="mini" type="primary" @click="showCreateDialog">
                    新增
                </el-button>

                <el-button size="mini" :loading="$attrs.isSubmitting" @click="$emit('save')">保存</el-button>
            </template>

            <FormWithDialog
                ref="form"
                v-model="formDialog.draft"
                :visible.sync="formDialog.visible"
                :confirmText="formDialogConfirmBtnText"
                :schoolTypeOptions="educationalLevelOptions"
                @cancel="closeFormDialog"
                @confirm="handleFormConfirm"
            />

            <el-table :data="educationalExperienceFormatted" border style="width: 100%">
                <el-table-column align="center" prop="schoolName" label="学校名称" />
                <el-table-column align="center" prop="schoolType" label="类型" />
                <el-table-column align="center" prop="major" label="所学专业" />
                <el-table-column align="center" prop="beginDate" label="其实日期" />
                <el-table-column align="center" prop="endDate" label="结束日期" />
                <el-table-column align="center" prop="certificate" label="证书" />
                <el-table-column align="center" prop="certificateNo" label="证书编号" />

                <el-table-column align="center" label="操作" v-if="isEditing">
                    <template slot-scope="scope">
                        <div class="row-actions">
                            <el-button
                                size="mini"
                                type="text"
                                @click="handleEditing(scope.$index,scope.row)"
                            >
                                编辑
                            </el-button>

                            <Popconfirm
                                :confirmFn="deleteRecord(scope.$index)"
                                title="确定删除吗？"
                            >
                                <el-button
                                    size="mini"
                                    type="text"
                                >
                                    删除
                                </el-button>
                            </Popconfirm>
                        </div>
                    </template>
                </el-table-column>

            </el-table>
        </Block>
    </div>
</template>

<style lang="scss">
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: nowrap;
    padding: 20px 0;

    >.title {
        font-size: 16px;
        font-weight: 700;
        color: #303133;
    }

    >.actions {}
}
</style>
